<?php

namespace Wechat\Controller;

class OrderController extends CommonController {

    public function index() {

        $id = $_REQUEST["id"];

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("product/index"));
        }

        $category = D("Category")->queryById($product["category_id"]);

        if($category["is_finished"] != C("DEFAULT_YN.YES")) {
            $this->redirect(U("product/index"));
        }

//        if($category["need_doctor"] == 1) {
//
//            if(isNullOrEmpty($this->customer["doctor_name"])
//                || isNullOrEmpty($this->customer["hospital_name"])) {
//                $this->assign("confirmInfo", 1);
//            }
//
//        }
        $this->assign("category", $category);
        //产品是否属于病例资料中所选病症
//        if($product["category_id"] == $this->customer["category_id"])
            $this->assign("customer", $this->customer);

        $this->assign("product", $product);
        $this->display("index");

    }

    public function measureInfo() {

        $id = $_REQUEST["id"];

        $orderMap["customer_id"] = $this->customer["customer_id"];
        $orderMap["order_id"] = $id;

        $order = D("Order")->queryByMap($orderMap);

        if(isNullOrEmpty($order)) {
            $this->redirect(U("userCenter/index"));
        }

        $product = D("Product")->queryById($order["product_id"]);
        $order["measure_data"] = json_decode(html_entity_decode($order["measure_data"]) ,true);

        $this->assign("product", $product);
        $this->assign("order", $order);
        $this->display("measureInfo");

    }

    public function measure() {

        $id = $_REQUEST["id"];

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("product/index"));
        }

        $category = D("Category")->queryById($product["category_id"]);

        if($category["is_finished"] != C("DEFAULT_YN.YES")) {
            $this->redirect(U("product/index"));
        }

        if($product["need_measure"] != C("DEFAULT_YN.YES")) {
            $this->redirect(U("order/index", array("id"=>$id)));
        }

        $product["measure_json"] = unserialize($product["measure_json"]);

        $this->assign("product", $product);
        $this->display("measure");

    }

    public function createOrder() {

        $productId = $_REQUEST["productId"];
        $product = D("Product")->queryById($productId);

        $data["code"] = 200;

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }

        $category = D("Category")->queryById($product["category_id"]);

        if($category["is_finished"] != C("DEFAULT_YN.YES")) {
            $data["code"] = -2;
            $data["msg"] = "商品不是成品，请预约";
            echo json_encode($data);
            exit();
        }

        $orderData["create_time"] = getCurrentDate();
        $orderData["product_id"] = $productId;
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["need_invoice"] = I("post.needInvoice");
        $orderData["invoice_name"] = I("post.invoiceName");
        $orderData["invoice_number"] = I("post.invoiceNumber");
        $orderData["receive_name"] = I("post.receiveName");
        $orderData["receive_address"] = I("post.receiveAddress");
        $orderData["receive_contact"] = I("post.receiveContact");
        $orderData["number"] = I("post.number");
        $orderData["size"] = I("post.size");
        $orderData["patient_name"] = I("post.patientName");
        $orderData["doctor_name"] = I("post.doctorName");
        $orderData["hospital_name"] = I("post.hospitalName");
        if($product["category_id"] == 2){
            $orderData["price"] = $product["price"]*$orderData["number"] - $this->customer["point"];
//            $orderData["price"] = $product["price"]*$orderData["number"] - $this->customer["point"] * 2;
        }else{
            $orderData["price"] = $product["price"]*$orderData["number"];
        }

        $orderData["note"] = I("post.note");
        $orderData["delivery_type"] = I("post.deliveryType");
        $orderData["need_measure"] = I("post.needMeasure");
        $orderData["measure_data"] = I("post.measureData");

        if($product["product_id"] == 2) {
            $measureData = json_decode(html_entity_decode($orderData["measure_data"]) ,true);
            $orderData["measure_result"] = calculateIowaData($measureData[0]["value"]);
        } elseif($product["product_id"] == 5) {
            $measureData = json_decode(html_entity_decode($orderData["measure_data"]) ,true);
            $orderData["measure_result"] = calculateDRAFO(
                $measureData[0]["value"], $measureData[2]["value"],
                $measureData[1]["value"]);

        }


        $out_trade_no = "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1);
        $payId = D('Pay')->add(array(
            'out_trade_no' => $out_trade_no,
            'money' => $orderData["price"],
            'status' => 0,
            'type' => 1,
            'callback' => "",
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate(),
            'pay_source' => 1
        ));

        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        //该产品是否需要医生
        if($category["need_doctor"] == 1) {
            $customerInfo = D("Customer")->queryById($this->customer["customer_id"]);
            $customerInfo["category_id"] = $product["category_id"];
            $customerInfo["doctor_name"] = I("post.doctorName");
            $customerInfo["hospital_name"] = I("post.hospitalName");
            D("Customer")->updateInfo($customerInfo);
        }
        $customerInfo = D("Customer")->queryById($this->customer["customer_id"]);
        if($product["product_id"] == 2){
            $customerInfo["point"] = 0;
        }

        D("Customer")->updateInfo($customerInfo);
        $data["order_id"] = $orderId;

        //推送信息
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=0";
        $notifyData["first"] = "您已下订单，请支付";
        $notifyData["keyword1"] = $product["product_name"]."，共 ".$orderData["number"]." 件";
        $notifyData["keyword2"] = $out_trade_no;
        $notifyData["keyword3"] = $orderData["price"]." 元";
        $notifyData["remark"] = "点击查看订单详情。";

        $notifyData["openid"] = $this->customer["openid"];
        OrderUnpaidNotify($notifyData);

        echo json_encode($data);

    }

    public function couponOrder() {
        $couponCode = $_REQUEST["couponCode"];
        $coupon = D("Coupon")->where(array('coupon_code'=>$couponCode))->find();

        if(isNullOrEmpty($coupon)){
            $this->error("无效产品！");
            exit();
        }

        $order = D('Order')->where(array('order_id' => $coupon["order_id"]))->find();
        if (!isNullOrEmpty($order)) {
            if ($order["status"] > 0) {
                $this->error("已售出产品！");
                exit();
            }
        }

        $product = D("Product")->queryById($coupon["product_id"]);
        $this->assign("customer", $this->customer);
        $this->assign("product", $product);
        $this->assign("coupon", $coupon);
        $this->display("couponOrder");
    }

    public function createCouponOrder() {
        $couponCode = $_REQUEST["couponCode"];
        $coupon = D("Coupon")->where(array('coupon_code'=>$couponCode))->find();
        if(isNullOrEmpty($coupon)){
            $data["code"] = -1;
            $data["msg"] = "无效产品链接";
            echo json_encode($data);
            exit();
        }
        $order = D('Order')->where(array('coupon_code' => $coupon["coupon_code"]))->order("order_id desc")->find();
        if (!isNullOrEmpty($order)) {
            if ($order["status"] > 0) {
                $data["code"] = -1;
                $data["msg"] = "已售出产品";
                echo json_encode($data);
                exit();
            }else{
                $minute=floor((strtotime(getCurrentDate())-strtotime($order["create_time"]))%86400/60);
                if ($order["customer_id"] == $this->customer["customer_id"] && $minute < 1) {
                    $data["code"] = -2;
                    $data["msg"] = "重复下单，请1分钟后再试";
                    echo json_encode($data);
                    exit();
                }
            }
        }

        $product = D("Product")->queryById($coupon["product_id"]);

        $data["code"] = 200;

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "商品不存在";
            echo json_encode($data);
            exit();
        }
        $orderData["product_id"] = $product["product_id"];
        $orderData["size"] = $coupon["size"];
        $orderData["customer_id"] = $this->customer["customer_id"];
        $orderData["patient_name"] = I("post.patientName");
        $orderData["need_invoice"] = I("post.needInvoice");
        $orderData["invoice_name"] = I("post.invoiceName");
        $orderData["invoice_number"] = I("post.invoiceNumber");
        $orderData["receive_name"] = I("post.receiveName");
        $orderData["receive_address"] = I("post.receiveAddress");
        $orderData["receive_contact"] = I("post.receiveContact");
        $orderData["doctor_name"] = $coupon["default_doctor_name"];
        $orderData["hospital_name"] = $coupon["default_hospital_name"];
        $orderData["note"] = I("post.note");
        $orderData["create_time"] = getCurrentDate();
        $orderData["price"] = $coupon["price"];
        $orderData["number"] = $coupon["number"];
        $orderData["coupon_code"] = $couponCode;
//        $orderData["delivery_type"] = I("post.deliveryType");
//        $orderData["need_measure"] = I("post.needMeasure");

        $out_trade_no = "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1);
        $payId = D('Pay')->add(array(
            'out_trade_no' => $out_trade_no,
            'money' => $orderData["price"],
            'status' => 0,
            'type' => 1,
            'callback' => "",
            'create_time' => getCurrentDate(),
            'update_time' => getCurrentDate(),
            'pay_source' => 1
        ));
        $orderData["pay_id"] = $payId;

        $orderId = D("Order")->add($orderData);

        $coupon["order_id"] = $orderId;
        $coupon["used"] = 1;
        $coupon["update_time"] = getCurrentDate();
        D("Coupon")->updateInfo($coupon);

        $data["order_id"] = $orderId;
        $data["coupon_code"] = $couponCode;

        //推送信息
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=0";
        $notifyData["first"] = "您已下订单，请支付";
        $notifyData["keyword1"] = $product["product_name"]."，共 ".$orderData["number"]." 件";
        $notifyData["keyword2"] = $out_trade_no;
        $notifyData["keyword3"] = $orderData["price"]." 元";
        $notifyData["remark"] = "点击查看订单详情。";

        $notifyData["openid"] = $this->customer["openid"];
        OrderUnpaidNotify($notifyData);

        echo json_encode($data);

    }

    public function groupOrder() {
        $orderId = $_REQUEST["orderId"];
        $status = $_REQUEST["status"];
        if(isNullOrEmpty($orderId)){
            $id = $_REQUEST["id"];
            $product = D("Product")->queryById($id);

            if(isNullOrEmpty($product) || $product["group_status"] == ""){
                $this->error("暂无团购！");
                exit();
            }

            $groupOrder = D('GroupOrder')->alias("go")
                ->join("left join __ORDER__ o on o.order_id = go.order_id")
                ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
                ->join("left join __CUSTOMER__ cus on cus.customer_id = o.customer_id")
                ->where(array('o.product_id' => $product["product_id"], 'go.group_code' => $product["group_code"], 'o.customer_id' => $this->customer["customer_id"]))
                ->field("go.*, p.product_name, p.image_url, cus.nickname, o.size, o.number, o.status, o.patient_name, o.pay_time, o.need_invoice, o.invoice_name, o.invoice_number, o.receive_name, o.receive_contact, o.receive_address,o.express_company, o.delivery_number, o.outstock_time, o.note")
                ->find();

            if($status == "-1" && $product["group_status"] == 1 && isNullOrEmpty($groupOrder)){
                $this->error("很抱歉，您未预订，无法购买此产品");
                exit();
            }
        }else{
            $groupOrder = D('GroupOrder')->alias("go")
                ->join("left join __ORDER__ o on o.order_id = go.order_id")
                ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
                ->join("left join __CUSTOMER__ cus on cus.customer_id = o.customer_id")
                ->where(array('o.order_id' => $orderId, 'o.customer_id' => $this->customer["customer_id"]))
                ->field("go.*, p.product_id, p.product_name, p.image_url, cus.nickname, o.size, o.number, o.status, o.patient_name, o.pay_time, o.need_invoice, o.invoice_name, o.invoice_number, o.receive_name, o.receive_contact, o.receive_address,o.express_company, o.delivery_number, o.outstock_time, o.note")
                ->find();

            $product = D("Product")->queryById($groupOrder["product_id"]);
            if(isNullOrEmpty($groupOrder)){
                $this->error("很抱歉，您未预订，无法购买此产品");
                exit();
            }
        }

        if(isNullOrEmpty($groupOrder["number"])){
            $groupOrder["number"] = 0;
        }
        $this->assign("status", $status);
        $this->assign("customer", $this->customer);
        $this->assign("product", $product);
        $this->assign("groupOrder", $groupOrder);
        $this->assign("orderId", $orderId);
        $this->display("groupOrder");
    }

    public function createGroupOrder() {
        $status = I("post.status");
        $id = I("post.productId");
        $orderId = I("post.orderId");
        if(isNullOrEmpty($orderId)) {
            $product = D("Product")->queryById($id);
            if (isNullOrEmpty($product) || $product["group_status"] == "") {
                $data["code"] = -1;
                $data["msg"] = "无效产品";
                echo json_encode($data);
                exit();
            }

            $orderData = D('Order')->where(array('product_id' => $product["product_id"], 'group_code' => $product["group_code"], 'customer_id' => $this->customer["customer_id"]))->find();
            if (!isNullOrEmpty($orderData) && $product["group_status"] == -1 && $status == -2) {
                $data["code"] = -1;
                $data["msg"] = "您已预订，请等待开团";
                echo json_encode($data);
                exit();
            }
            if (!isNullOrEmpty($orderData) && $product["group_status"] == 1) {
                $data["code"] = -1;
                $data["msg"] = "您已购买，不能重复购买";
                echo json_encode($data);
                exit();
            }
        }else{
            $orderData = D('Order')->queryById($orderId);
            if (isNullOrEmpty($orderData)) {
                $data["code"] = -1;
                $data["msg"] = "无效订单";
                echo json_encode($data);
                exit();
            }
            $product = D("Product")->queryById($orderData["product_id"]);
        }
        $data["code"] = 200;

        $orderData["status"] = $status;
        $orderData["number"] = I("post.number");
        $orderData["size"] = I("post.size");
        $orderData["patient_name"] = I("post.patientName");
//        $orderData["need_invoice"] = I("post.needInvoice");
//        $orderData["invoice_name"] = I("post.invoiceName");
//        $orderData["invoice_number"] = I("post.invoiceNumber");
        $orderData["receive_name"] = I("post.receiveName");
        $orderData["receive_address"] = I("post.receiveAddress");
        $orderData["receive_contact"] = I("post.receiveContact");
//        $orderData["doctor_name"] = I("post.doctorName");
//        $orderData["hospital_name"] = I("post.hospitalName");
        $orderData["note"] = I("post.note");

//        $orderData["delivery_type"] = I("post.deliveryType");
//        $orderData["need_measure"] = I("post.needMeasure");

        if($status == "-2") {
            $orderData["group_code"] = $product["group_code"];
            $orderData["create_time"] = getCurrentDate();
            $orderData["product_id"] = I("post.productId");
            $orderData["customer_id"] = $this->customer["customer_id"];
            $orderId = D("Order")->add($orderData);
            $groupOrder["order_id"] = $orderId;
            $groupOrder["group_code"] = $product["group_code"];
            $groupOrder["create_time"] = getCurrentDate();
            $groupOrder["update_time"] = getCurrentDate();
            D("GroupOrder")->add($groupOrder);

            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=-2";
            $notifyData["first"] = "您已预订成功，请等待开团";
            $notifyData["keyword1"] = $product["product_name"]."，共 ".$orderData["number"]." 件";
            $notifyData["keyword2"] = "预订团购成功";
            $notifyData["keyword3"] = getCurrentDate();;
            $notifyData["remark"] = "点击查看团购订单。";
            $notifyData["openid"] = $this->customer["openid"];
            progressNotify($notifyData);

            $notifyData["url"] = "";
            $notifyData["first"] = "收到预订团购订单";
            if(!isNullOrEmpty($this->customer["realname"])){
                $notifyData["first"] .= "，用户：" . $this->customer["realname"];
            }else{
                $notifyData["first"] .= "，用户：" . $this->customer["nickname"];
            }
            $notifyData["remark"] = "患者姓名：" . $orderData["patient_name"] . "，地址：" . $orderData["receive_address"];
//            $adminRoleArr = array("1","8","10");
//            $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
            $openidArray = getNotifyArrByName("createGroupOrder", "xWk202003270001");
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                progressNotify($notifyData);
            }
        }

        if($status == "-1"){
            $groupOrder = D("GroupOrder")->where(array('order_id' => $orderId))->find();
            $groupOrder["update_time"] = getCurrentDate();
            D("GroupOrder")->updateInfo($groupOrder);

            $orderData["price"] = $product["group_price"];
            $out_trade_no = "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1);
            $payId = D('Pay')->add(array(
                'out_trade_no' => $out_trade_no,
                'money' => $orderData["price"],
                'status' => 0,
                'type' => 1,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));
            $orderData["pay_id"] = $payId;
            D("Order")->updateInfo($orderData);
            $data["order_id"] = $orderData["order_id"];
            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=0";
            $notifyData["first"] = "您已下订单，请支付";
            $notifyData["keyword1"] = $product["product_name"]."，共 ".$orderData["number"]." 件";
            $notifyData["keyword2"] = $out_trade_no;
            $notifyData["keyword3"] = $orderData["price"]." 元";
            $notifyData["remark"] = "点击查看订单详情。";

            $notifyData["openid"] = $this->customer["openid"];
            OrderUnpaidNotify($notifyData);
        }

        if($status == "1"){
            $orderData["group_code"] = $product["group_code"];
            $orderData["create_time"] = getCurrentDate();
            $orderData["product_id"] = I("post.productId");
            $orderData["customer_id"] = $this->customer["customer_id"];
            $orderData["price"] = $product["group_price"];
            $out_trade_no = "PAID".date('Ymd',time()) . sprintf("%03d", substr(D("Pay")->count(), -3, 3)+1);
            $payId = D('Pay')->add(array(
                'out_trade_no' => $out_trade_no,
                'money' => $orderData["price"],
                'status' => 0,
                'type' => 1,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => 1
            ));
            $orderData["status"] = -1;
            $orderData["pay_id"] = $payId;
            $orderId = D("Order")->add($orderData);

            $groupOrder["order_id"] = $orderId;
            $groupOrder["group_code"] = $product["group_code"];
            $groupOrder["create_time"] = getCurrentDate();
            $groupOrder["update_time"] = getCurrentDate();
            D("GroupOrder")->add($groupOrder);

            $data["order_id"] = $orderId;
            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=0";
            $notifyData["first"] = "您已下订单，请支付";
            $notifyData["keyword1"] = $product["product_name"]."，共 ".$orderData["number"]." 件";
            $notifyData["keyword2"] = $out_trade_no;
            $notifyData["keyword3"] = $orderData["price"]." 元";
            $notifyData["remark"] = "点击查看订单详情。";

            $notifyData["openid"] = $this->customer["openid"];
            OrderUnpaidNotify($notifyData);
        }

        echo json_encode($data);

    }
}